/**
 * This file is part of 1genia trampoline
 * Copyright (C) 2007 1genia (contact@1genia.com)
 *
 * This library is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; version 3 of the License. 
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details. 
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; see the file COPYING.TXT.  If not,
 * write to the Free Software Foundation, Inc., 51 Franklin Street,
 * Fifth Floor, Boston, MA 02110-1301, USA. 
 **/
package com.genia.toolbox.web.mvc.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;

import com.genia.toolbox.basics.bean.DataContainer;
import com.genia.toolbox.basics.bean.DataContainerCache;
import com.genia.toolbox.basics.exception.BundledException;
import com.genia.toolbox.basics.exception.technical.TechnicalException;
import com.genia.toolbox.basics.manager.ExceptionManager;
import com.genia.toolbox.basics.manager.StreamManager;
import com.genia.toolbox.web.constant.HttpHeader;

/**
 * an abstract controller to allow the user to download files.
 * 
 * @param <COMMAND>
 *          the type of the command
 */
public abstract class AbstractDownloadController<COMMAND>
    extends AbstractCustomFormController
{

  /**
   * the <code>Log</code> variabe.
   */
  private static final Logger LOGGER = LoggerFactory.getLogger(AbstractDownloadController.class);

  /**
   * whether to allow the browser to cache the returned document.
   */
  private boolean caching = false;

  /**
   * the {@link DataContainerCache} to use.
   */
  private DataContainerCache dataContainerCache;

  /**
   * the {@link ExceptionManager} to use.
   */
  private ExceptionManager exceptionManager;

  /**
   * the {@link StreamManager} to use.
   */
  private StreamManager streamManager;



  /**
   * constructor.
   */
  public AbstractDownloadController()
  {
    setCaching(false);
  }



  /**
   * returns the cache entry associated to the given command, or
   * <code>null</code> if the entry must not be cached.
   * 
   * @param command
   *          the form containing the parameter of the request
   * @return the cache entry associated to the given command, or
   *         <code>null</code> if the entry must not be cached
   */
  public String getCacheEntry(COMMAND command)
  {
    return null;
  }



  /**
   * returns the {@link DataContainer} to display.
   * 
   * @param form
   *          the form containing the parameter of the request
   * @return the {@link DataContainer} to display or <code>null</code> if no
   *         such object exists
   * @throws BundledException
   *           when an error occured
   */
  public abstract DataContainer getDataContainer(COMMAND form)
      throws BundledException;



  /**
   * getter for the dataContainerCache property.
   * 
   * @return the dataContainerCache
   */
  public DataContainerCache getDataContainerCache()
  {
    return dataContainerCache;
  }



  /**
   * getter for the exceptionManager property.
   * 
   * @return the exceptionManager
   */
  public ExceptionManager getExceptionManager()
  {
    return exceptionManager;
  }



  /**
   * getter for the streamManager property.
   * 
   * @return the streamManager
   */
  public StreamManager getStreamManager()
  {
    return streamManager;
  }



  /**
   * getter for the caching property.
   * 
   * @return the caching
   */
  public final boolean isCaching()
  {
    return caching;
  }



  /**
   * Process form submission request. This method retrieve the
   * {@link DataContainer} of the uploaded file to preview and returns it.
   * 
   * @param request
   *          current servlet request
   * @param response
   *          current servlet response
   * @param form
   *          form object with request parameters bound onto it
   * @param bindException
   *          holder without errors (subclass can add errors if it wants to)
   * @return always <code>null</code>
   * @throws TechnicalException
   *           when an error occurred
   * @see org.springframework.web.servlet.mvc.AbstractFormController#processFormSubmission(javax.servlet.http.HttpServletRequest,
   *      javax.servlet.http.HttpServletResponse, java.lang.Object,
   *      org.springframework.validation.BindException)
   */
  @Override
  protected final ModelAndView processFormSubmission(HttpServletRequest request, HttpServletResponse response, Object form, BindException bindException)
      throws TechnicalException
  {
    try {
      @SuppressWarnings("unchecked")
      COMMAND command = (COMMAND) form;
      DataContainer dataContainer = null;
      String cacheEntry = getCacheEntry(command);
      if (cacheEntry != null && getDataContainerCache() != null) {
        dataContainer = getDataContainerCache().getDataContainer(cacheEntry);
        if (dataContainer == null) {
          dataContainer = getDataContainer(command);
          getDataContainerCache().setDataContainer(cacheEntry, dataContainer);
        }
      }
      else {
        dataContainer = getDataContainer(command);
      }
      if (dataContainer == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return null;
      }
      response.setStatus(HttpServletResponse.SC_OK);
      response.setContentType(dataContainer.getContentType());
      response.setHeader(HttpHeader.CONTENT_DISPOSITION, "inline; filename=" + dataContainer.getName());
      if (isCaching()) {
        response.setDateHeader(HttpHeader.LAST_MODIFIED, getApplicationContext().getStartupDate());
      }
      else {
        response.setDateHeader(HttpHeader.LAST_MODIFIED, System.currentTimeMillis());
      }
      getStreamManager().copyStream(dataContainer.getInputStream(), response.getOutputStream());
      response.getOutputStream().close();
      return null;
    }
    catch (Exception e) {
      throw getExceptionManager().convertException(e);
    }

  }



  /**
   * setter for the caching property.
   * 
   * @param caching
   *          the caching to set
   */
  public final void setCaching(boolean caching)
  {
    this.caching = !LOGGER.isDebugEnabled() && caching;
    setCacheSeconds(caching ? 31 * 24 * 3600 : 0);
    setUseCacheControlHeader(!caching);
  }



  /**
   * setter for the dataContainerCache property.
   * 
   * @param dataContainerCache
   *          the dataContainerCache to set
   */
  public void setDataContainerCache(DataContainerCache dataContainerCache)
  {
    this.dataContainerCache = dataContainerCache;
  }



  /**
   * setter for the exceptionManager property.
   * 
   * @param exceptionManager
   *          the exceptionManager to set
   */
  public void setExceptionManager(ExceptionManager exceptionManager)
  {
    this.exceptionManager = exceptionManager;
  }



  /**
   * setter for the streamManager property.
   * 
   * @param streamManager
   *          the streamManager to set
   */
  public void setStreamManager(StreamManager streamManager)
  {
    this.streamManager = streamManager;
  }
}